<template>
  <div>
    <Dialog
      v-model="showDialog"
      title="配置报名信息"
      :width="500"
      @confirm="submitForm"
      @close="cancel"
      @open="openDialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字段标题" prop="name">
          <el-input
            v-model="form.name"
            maxlength="10"
            show-word-limit
            clearable
            placeholder="请输入字段标题"
          >
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="提示文字" prop="placeholder">
          <el-input
            v-model="form.placeholder"
            maxlength="20"
            show-word-limit
            clearable
            placeholder="请输入提示文字"
          >
          </el-input>
        </el-form-item> -->
        <el-form-item label="字段类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio v-for="(item, idx) in typeList" :key="idx" :label="item.id">{{
              item.name
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="form.type == 'radio' || form.type == 'check'">
          <div class="enumeration" v-for="(item, idx) in form.selectData" :key="idx">
            <el-form-item
              :label="`选项${idx + 1}`"
              :placeholder="`请输入选项${idx + 1}`"
              :prop="'selectData.' + idx + '.value'"
              :rules="rules.value"
            >
              <el-input
                type="text"
                maxlength="10"
                show-word-limit
                :placeholder="`请输入选项${idx + 1}`"
                v-model="item.value"
              >
              </el-input>
            </el-form-item>
            <div class="operation">
              <div>
                <el-icon @click="addValue(idx)"><CirclePlus /></el-icon>
              </div>
              <div>
                <el-icon @click="delValue(idx)"><Remove /></el-icon>
              </div>
            </div>
          </div>
        </div>

        <el-form-item label="是否必填" prop="isMandatory">
          <el-radio-group v-model="form.isMandatory">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>
<script lang="ts" setup>
import { deepClone } from "@/utils";
const props = withDefaults(
  defineProps<{
    showDialog: boolean;
    isEdit: boolean;
    dataItem: object;
    fieldConfig: string[];
  }>(),
  {}
);
const { showDialog, dataItem, isEdit, fieldConfig } = toRefs(props);
const typeList = ref([
  { id: "input", name: "单行文本" },
  { id: "textarea", name: "多行文本" },
  { id: "radio", name: "单项选择" },
  { id: "check", name: "多项选择" },
  { id: "number", name: "数值输入" },
  { id: "date", name: "日期" },
  { id: "area", name: "省市区" },
]);
const formRef = ref();
const form = ref({
  name: "",
  //   placeholder: "",
  value: "",
  type: "input",
  isMandatory: 1,
  selectData: [
    {
      value: "",
    },
  ],
} as any);
const rules = ref({
  name: [{ required: true, message: "请输入字段标题", trigger: "blur" }],
  value: [{ required: true, message: "请输入选项", trigger: "blur" }],
});
const addValue = (idx: number) => {
  form.value.selectData.splice(idx + 1, 0, { value: "" });
};
const delValue = (idx: number) => {
  form.value.selectData.splice(idx, 1);
};

const openDialog = () => {
    // console.log('[ indexItem ]', indexItem.value)
  if (dataItem.value["name"]) {
    form.value = deepClone(dataItem.value);
  }
};

// 校验重名
const checkRepeat = (data: any) => {
  console.log('[ dataItem.value ]', dataItem.value)
  let isCheck = false
  fieldConfig.value.forEach((item: any)=>{
    if(isEdit.value) {
      if(item.name == data.name && item.name !== dataItem.value.name) {
        isCheck = true
      }
    } else {
      if(item.name == data.name) {
        isCheck = true
      }
    }
    
  })
  return isCheck
}

const submitForm = async () => {
  await formRef.value.validate((valid: any) => {
    if (valid) {
      if(checkRepeat(form.value)) {
        ElMessage.warning('字段名称重复，请检查字段名称')
      } else {
        if(isEdit.value) {
          edit();
        } else {
          confirm();
        }
      }
      
      
    }
  });
};
const edit = () => {
  let params = JSON.parse(JSON.stringify(form.value))
  // 保证移动端多选时绑定的状态数据
  if(params.type == 'check') {
    params.value = []
  }
  emit("edit", deepClone(params));
  cancel();
}
const confirm = () => {
  let params = JSON.parse(JSON.stringify(form.value))
  // 保证移动端多选时绑定的状态数据
  if(params.type == 'check') {
    params.value = []
  }
  emit("confirm", deepClone(params));
  cancel();
};
const cancel = () => {
  emit("cancel");
  formRef.value.resetFields();
  form.value = {
    name: "",
    //   placeholder: "",
    type: "input",
    isMandatory: 1,
    selectData: [
      {
        value: "",
      },
    ],
  };
};
const emit = defineEmits(["confirm", "cancel", "edit"]);
</script>
<style lang="scss" scoped>
.enumeration {
  display: flex;
  .el-input {
    flex: 1;
  }
  .operation {
    width: 50px;
    font-size: 18px;
    margin: 0 0 18px 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    // flex: 1;
    .el-icon {
      cursor: pointer;
      flex: 1;
    }
    .el-icon:hover {
      color: var(--el-color-primary);
    }
  }
}
</style>
